<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height: 60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="hAdd"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="list">
              <el-table-column label="序号" width="120" type="index" />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template #default="{ row }">
                  <el-button size="small" type="success" @click="hAssign(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="hEdit(row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="hDel(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination
                :current-page="pageParams.page"
                :page-sizes="[2,4,6,8,10]"
                :page-size="pageParams.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 新增弹框 -->
      <el-dialog
        :title="isEdit ? '编辑角色' : '新增角色'"
        :visible.sync="showDialog"
        @close="hClose"
      >
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="hClose">取消</el-button>
            <el-button size="small" type="primary" @click="hSubmit">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>
      <!-- 分配权限的弹层 -->
      <el-dialog
        title="分配权限(一级为路由页面查看权限-二级为按钮操作权限)"
        :visible.sync="showDialogAssign"
      >
        <assign-permission v-if="showDialogAssign" ref="assignRole" :role-id="roleId" @close="showDialogAssign=false" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import assignPermission from './assignPermission'
import { addRoles, editRoles, getRoles, delRoles } from '@/api/settings'
export default {
  components: {
    assignPermission
  },
  data() {
    return {
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '请输入角色描述', trigger: 'blur' }]
      },
      showDialog: false,
      showDialogAssign: false, // 分配权限对话框
      // 保存角色列表
      list: [],
      pageParams: {
        page: 1, // 页码值
        pagesize: 2// 每页显示的条数
      },
      total: 0, // 总的数据条数
      isEdit: false,
      roleId: ''
    }
  },
  created() {
    this.loadRoles()
  },
  methods: {
    hAssign(id) {
      // alert(id)
      // 1. 保存角色编号
      //    它会影响子组件中的props,但是，这个传递的过程是异步的
      this.roleId = id
      // 2. 弹层
      this.showDialogAssign = true
      // 3. 手动调用子组件的loadPermissionByRoleId， 去根据最新的roleId获取权限信息
      this.$nextTick(() => {
        this.$refs.assignRole.loadPermissionByRoleId()
      })
    },
    // 关闭弹层
    hClose() {
      console.log('弹层关闭')
      // 清空表单
      this.$refs.roleForm.resetFields()
      // 手动清空
      this.roleForm = {
        name: '',
        description: ''
      }
      this.showDialog = false
    },
    // 确认提交
    hSubmit() {
      this.$refs.roleForm.validate(valid => {
        if (!valid) return // 验证没有通过
        // 验证通过
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    hEdit(row) {
      console.log('row', row)
      this.roleForm = { ...row } // 使用浅拷贝
      this.isEdit = true
      this.showDialog = true
    },
    hAdd() {
      this.isEdit = false
      this.showDialog = true
    },
    hDel(id) {
      this.$confirm('您确定要删除这个角色吗?').then(async() => {
        const res = await delRoles(id)
        if (this.list.length === 1) {
          this.pageParams.page--
          if (this.pageParams.page <= 0) {
            this.pageParams.page = 1
          }
        }
        console.log(res, 'delRole')
        if (res.code === 10000) {
          // 1. 提示
          this.$message({ type: 'success', message: '删除成功!' })
          // 2. 更新数据
          this.loadRoles()
        }
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消删除' })
      })
    },
    async doDel(id) {
      try {
        const res = await delRoles(id)
        console.log(res)
        // 1. 提示
        this.$message({ type: 'success', message: '删除成功!' })
        // 2. 更新数据
        this.loadDepartments()
      } catch (err) {
        console.log(err)
        this.$message({ type: 'error', message: '删除失败' })
      }
    },
    async doAdd() {
      try {
        const res = await addRoles(this.roleForm)
        console.log(res)
        // 新增数据完成,将总数加1
        this.total++
        // 计算最大的页码值: Math.ceil总条数/每页显示的条数
        const maxPage = Math.ceil(this.total / this.pageParams.pagesize)
        this.pageParams.page = maxPage
        this.loadRoles()
        this.$message.success('添加成功')
        this.showDialog = false
      } catch (error) {
        this.$message.error('添加失败')
        console.log(error)
      }
    },
    async doEdit() {
      try {
        await editRoles(this.roleForm)
        this.$message({ type: 'success', message: '修改成功' })
        this.$emit('success')
      } catch (err) {
        console.log(err)
        this.$message({ type: 'error', message: err })
      }
    },
    // 当每页显示的条数进行切换时触发 ---> val :每页显示的条数
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.pageParams.page = 1
      this.pageParams.pagesize = val
      this.loadRoles()
    },
    // 当期的页码值进行切换时触发 ---> val :当前的页码值
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.pageParams.page = val
      this.loadRoles()
    },
    async loadRoles() {
      try {
        const res = await getRoles(this.pageParams)
        console.log(res)
        this.list = res.data.rows
        this.total = res.data.total
      } catch (error) {
        this.$message.error(error)
      }
    }
  }
}
</script>
